package com.wxy.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.school.common.R;
import com.wxy.school.dto.RateDto;
import com.wxy.school.entity.*;
import com.wxy.school.service.*;
import com.wxy.school.utils.OSSUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王祥宇
 * @projectName school
 * @packageName com.wxy.school.controller
 * @data 2023/4/16 15:14
 * @description: TODO
 * @version: 1.0
 */
@RestController
@RequestMapping("school/rate")
public class RateController {

    @Resource
    private RateService rateService;

    @Resource
    private UserService userService;

    @Resource
    private RateImgService rateImgService;

    @Resource
    private OrdersService ordersService;

    @Resource
    private ShopService shopService;

    @Resource
    private RateDishService rateDishService;

    @GetMapping("/getPage")
    public R<Page> getPage(int pageNum, int pageSize, String qurey, Long shopId){
        Page<Rate> ratePage = new Page<>(pageNum, pageSize);
        Page<RateDto> rateDtoPage = new Page<>();

        LambdaQueryWrapper<Rate> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (qurey != null && !qurey.isEmpty()){
            if (qurey.equals("匿") || qurey.equals("匿名") || qurey.equals("匿名用户")){
                lambdaQueryWrapper.eq(Rate::getIsHide, 1);
            }else {
                lambdaQueryWrapper.eq(Rate::getIsHide, 0);
                lambdaQueryWrapper.like(Rate::getUserName, qurey);
            }
        }
        lambdaQueryWrapper.orderByDesc(Rate::getRateTime);
        lambdaQueryWrapper.eq(Rate::getShopId, shopId);
        rateService.page(ratePage, lambdaQueryWrapper);
        BeanUtils.copyProperties(ratePage, rateDtoPage, "records");
        List<Rate> records = ratePage.getRecords();
        List<RateDto> rateDtoList = records.stream().map((item) -> {
            RateDto rateDto = new RateDto();
            BeanUtils.copyProperties(item, rateDto);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, item.getUserId());
            rateDto.setUser(userService.getOne(userLambdaQueryWrapper));
            LambdaQueryWrapper<RateImg> rateImgLambdaQueryWrapper = new LambdaQueryWrapper<>();
            rateImgLambdaQueryWrapper.eq(RateImg::getRateId, item.getId());
            rateDto.setRateImgList(rateImgService.list(rateImgLambdaQueryWrapper));
            return rateDto;
        }).collect(Collectors.toList());
        rateDtoPage.setRecords(rateDtoList);
        return R.success(rateDtoPage);
    }

    @GetMapping("/getAllRate")
    public R<List<RateDto>> getAll(Long shopId, Long dishId){
        List<Rate> rateList = null;
        if (shopId != null){
            LambdaQueryWrapper<Rate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Rate::getShopId, shopId);
            rateList = rateService.list(lambdaQueryWrapper);
        }
        if (dishId != null){
            LambdaQueryWrapper<RateDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(RateDish::getDishId, dishId);
            List<RateDish> rateDishList = rateDishService.list(lambdaQueryWrapper);
            rateList = rateDishList.stream().map((item) -> {
                LambdaQueryWrapper<Rate> rateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                rateLambdaQueryWrapper.eq(Rate::getId, item.getRateId());
                return rateService.getOne(rateLambdaQueryWrapper);
            }).collect(Collectors.toList());
        }
        List<RateDto> rateDtoList = rateList.stream().map(item -> {
            RateDto rateDto = new RateDto();
            BeanUtils.copyProperties(item, rateDto);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, item.getUserId());
            rateDto.setUser(userService.getOne(userLambdaQueryWrapper));
            LambdaQueryWrapper<RateImg> rateImgLambdaQueryWrapper = new LambdaQueryWrapper<>();
            rateImgLambdaQueryWrapper.eq(RateImg::getRateId, item.getId());
            rateDto.setRateImgList(rateImgService.list(rateImgLambdaQueryWrapper));
            return rateDto;
        }).collect(Collectors.toList());
        return R.success(rateDtoList);
    }

    @PostMapping("/addRate")
    public R<String> add(@RequestBody RateDto rateDto){
        Rate rate = new Rate();
        BeanUtils.copyProperties(rateDto, rate);
        int flag = rateDto.getRateScore().compareTo(BigDecimal.valueOf(2));
        if (flag > 0){
            rate.setIsGood(1);
        }else{
            rate.setIsGood(0);
        }
        rate.setRateTime(LocalDateTime.now());
        rateService.save(rate);
        if (rateDto.getIsRate() == 1){
            Orders orders = ordersService.getById(rateDto.getOrderId());
            orders.setIsRate(rateDto.getIsRate());
            ordersService.updateById(orders);
        }
        for (int i = 0; i < rateDto.getRateImgList().size(); i++){
            RateImg rateImg = new RateImg();
            BeanUtils.copyProperties(rateDto.getRateImgList().get(i), rateImg);
            rateImg.setRateId(rate.getId());
            rateImgService.save(rateImg);
        }
        for (int i = 0; i < rateDto.getRateDishList().size(); i++){
            RateDish rateDish = new RateDish();
            BeanUtils.copyProperties(rateDto.getRateDishList().get(i), rateDish);
            rateDish.setRateId(rate.getId());
            rateDishService.save(rateDish);
        }
        Long shopId = rateDto.getShopId();
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(Shop::getId, shopId);
        Shop shop = shopService.getOne(shopLambdaQueryWrapper);
        BigDecimal score = shop.getScore().add(rateDto.getRateScore()).divide(BigDecimal.valueOf(2), 1, RoundingMode.HALF_UP);
        shop.setScore(score);
        shopService.updateById(shop);
        return R.success("评价已发布");
    }

    @PutMapping("/updateRate")
    public R<String> update(@RequestBody RateDto rateDto){
        rateService.updateById(rateDto);
        return R.success("回复成功");
    }

    @DeleteMapping("/deleteRate/{rateId}")
    public R<String> delete(@PathVariable Long rateId){
        LambdaQueryWrapper<RateImg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RateImg::getRateId, rateId);
        List<RateImg> rateImgList = rateImgService.list(lambdaQueryWrapper);
        for (RateImg rateImg : rateImgList) {
            OSSUtils.deleteFile(rateImg.getRateImage());
        }
        rateImgService.removeBatchByIds(rateImgList);
        LambdaQueryWrapper<RateDish> rateDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        rateDishLambdaQueryWrapper.eq(RateDish::getRateId, rateId);
        List<RateDish> rateDishList = rateDishService.list(rateDishLambdaQueryWrapper);
        rateDishService.removeBatchByIds(rateDishList);
        rateService.removeById(rateId);
        return R.success("删除成功");
    }
}
